package com.nlecloud.bc.interceptor;

import com.nlecloud.bc.model.User;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author warrior
 * @description 存储认证token
 */
public class AuthTokenStorage {

    public static final String TOKEN_KEY = "Authorization";

    private static final String BEARER = "Bearer ";

    /**
     * 模拟session
     */
    private static final Map<String, User> JWT_USER = new HashMap<String, User>();

    /**
     * 全局获取用户
     */
    public static User getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getRequestHeaderToken(request);
        return JWT_USER.get(token);
    }

    /**
     * 设置用户
     */
    public static void setUser(String token, User user) {
        JWT_USER.put(token, user);
    }

    /**
     * 清除授权
     */
    public static void clearUser() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String token = getRequestHeaderToken(request);
        JWT_USER.remove(token);
    }

    /**
     * 获取请求头token
     * @param request
     * @return
     */
    public static String getRequestHeaderToken(HttpServletRequest request){
        String token = request.getHeader(TOKEN_KEY);
        if(!StringUtils.isEmpty(token) && token.contains(BEARER)){
            token = token.replace(BEARER,"");
        }
        return token;
    }
}
